package web.controller;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import dao.IDaoAsof;

import service.configuration.IConfiguration;
import service.associationmanager.IAssociationManager;
import service.authentification.Contributor;
import service.sheetmanager.ISheetManager;
import web.form.DelegationInfo;
import web.form.DelegationsList;
import web.form.SheetInfosList;
import web.form.SheetInfo;


/**
 * <b>ContributorPageController </b>
 * <p>ContributorPageController controle les requêtes pour l'espace contributeur.</p>
 * 
 */
@Controller
public class ContributorPageController {
	
	/**
     * Repr&eacute;sente le service de gestion de fiches
     */
	@Resource
	ISheetManager manager;
	
	/**
     * Repr&eacute;sente le service d'association entre fiches
     */
	@Resource
	IAssociationManager association;
	
	/**
     * Repr&eacute;sente le service de configuration
     */
	@Resource
	IConfiguration config;
	 
	/**
     * Repr&eacute;sente le service d'acces aux donnees
     */
	@Resource
	IDaoAsof dao;
	
	
	/**
     * Controlleur qui renvoi la page du contributeur
     */
	@RequestMapping(value = "/contributorPage.htm", method = RequestMethod.GET)
	public String showsList(@RequestHeader("Referer") String referer, HttpSession session, ModelMap model) throws MalformedURLException {
		Contributor user = (Contributor)session.getAttribute("user");
		URIParser uri = new URIParser(referer);
		if(user!=null){
			List <SheetInfo> ownedSheets = association.findOwnedSheet(user.getCode());
			List<DelegationInfo> receivedDelegations = association.findReceivedDelegations(user.getCode());
			List<DelegationInfo> givenDelegations = association.findGivenDelegations(user.getCode());
			
	
			if(!ownedSheets.isEmpty()) {
				model.addAttribute("ownedSheetsGroupedIndexes",
								   association.generateGroupedSheetInfosIndexes(ownedSheets));
				model.addAttribute("ownedSheets", new SheetInfosList(ownedSheets));
			}
			
			if(!receivedDelegations.isEmpty()) {
				model.addAttribute("receivedDelegationGroupedIndexes",
						association.generateGroupedDelegationsIndexes(receivedDelegations));
				model.addAttribute("receivedDelegations", new DelegationsList(receivedDelegations));
			}
			
			if(!givenDelegations.isEmpty()) {
				model.addAttribute("givenDelegationGroupedIndexes",
								   association.generateGroupedDelegationsIndexes(givenDelegations));
				model.addAttribute("givenDelegations", new DelegationsList(givenDelegations));
			}
			
			model.addAttribute("sheetLabelByType", config.getSheetLabelByType());
			model.addAttribute("personType", config.getPersonType());
			return "contributorPage";
		}else{
			if(uri.getPath().compareTo("contributorPage.htm")==0){
				return "redirect:home.htm";
			}
			uri.setParameter("login", "open");
			uri.removeParameter("register");
			return "redirect:"+uri.getUrl();
		}
			
	}
	
	/**
     * Controlleur qui effectue une delegation demandée sur la page contributeur
     */
	@RequestMapping(value = "/delegate.htm", method = RequestMethod.POST)
	public String onSubmitadddelegation(@RequestHeader("Referer")String referer,HttpSession session,
				@ModelAttribute("ownedSheets") SheetInfosList delegation,
				BindingResult result, ModelMap model) throws MalformedURLException, JSONException {
		JSONObject json = new JSONObject();
		Contributor user = (Contributor)session.getAttribute("user");
		if(user!=null){
			if(delegation.getPersonCode().compareTo("")!=0){
				if(user.getCode().compareTo(delegation.getPersonCode())!=0){
					List<String> listPersonCode = new ArrayList<String>(); 
					listPersonCode.add(delegation.getPersonCode());
					System.out.println("personnne"+delegation.getPersonCode());
					List<SheetInfo> listSheet=new ArrayList<SheetInfo>();
					for(SheetInfo sheet : delegation.getList()){
						if(sheet.isChecked()) {
							listSheet.add(sheet);
							System.out.println("ajout delegation : " + sheet.getCode() + " | " + sheet.getTitle());
						}
					}
					List<SheetInfo>impossibleDelegation=association.addDelegations(user, listPersonCode,listSheet);
					
					if(impossibleDelegation.isEmpty()){
						json.put("success", true);
						json.put("message", "délégation réussi.");
					}else{
						String impossibleDelegationsJson="<p>les délégations suivantes n'ont pas été effectuées :</p><ul>";
						
						for(SheetInfo sheet: impossibleDelegation){
							impossibleDelegationsJson+="<li>"+sheet.getCode()+" : "+sheet.getTitle()+"</li>";
						}
						impossibleDelegationsJson+="</ul>";
						json.put("success", false);
						json.put("reload", true);
						json.put("message", impossibleDelegationsJson);
					}
				}else{
					json.put("success", false);
					json.put("relaod", false);
					json.put("message", "<p>Erreur : vous ne pouvez pas déléguer une fiche a vous même!</p>");
				}
			}else{
				json.put("success", false);
				json.put("relaod", false);
				json.put("message", "<p>Erreur : Utilisateur inconnu!</p>");
			}
		
		}else{
			json.put("success", false);
			json.put("reload", true);
			json.put("message", "<p>Session expirée!</p>");
		}
		model.addAttribute("jsonArray", json);
		return "json";
	}
	
	/**
     * Controlleur qui supprime une liste de delegations
     */
	@RequestMapping(value ="/deleteDelegation.htm", method = RequestMethod.POST)
	public String onSubmitdeleteDelegation(@RequestHeader("Referer")String referer,HttpSession session,
			@ModelAttribute("givenDelegations") DelegationsList deleteDelegation,
			BindingResult result, ModelMap model) throws MalformedURLException {
		Contributor user = (Contributor)session.getAttribute("user");
		if(user!=null){
			List<DelegationInfo> deleteList = new ArrayList<DelegationInfo>();
			for(DelegationInfo delegation: deleteDelegation.getList()){
				if(delegation.isChecked()){
					System.out.println("suppression delegation : " + delegation.getId() + " | " + 
							 delegation.getSheetTitle());
					deleteList.add(delegation);
				}
			}
			association.removeDelegations(deleteList);
			
		}
		return "redirect:" + referer;
		
	}
	
	/**
     * Controlleur qui renvoi la page pour choisir une personne a qui on delegue un ensemble de fiches
     */
	@RequestMapping(value = "/selectPerson.htm", method = RequestMethod.GET)
	public String handleRequestRegister(@RequestHeader("Referer") String referer,
			HttpSession session, ModelMap model)  {
		
		if(referer!=null){
			return "selectPerson";
		}else{
			return "redirect : treeview.htm";
		}
			
	}
}
